package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.SceneryComment;
import cn.wolfcode.luowowo.comment.query.SceneryCommentQuery;
import cn.wolfcode.luowowo.comment.repository.ISceneryCommentRepository;
import cn.wolfcode.luowowo.comment.service.ISceneryCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class SceneryCommentServiceImpl implements ISceneryCommentService {

    @Autowired
    private ISceneryCommentRepository repository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(SceneryComment comment) {
        if (comment!=null) {
            comment.setCreateTime(new Date());
        }
        repository.save(comment);
    }

    @Override
    public Page query(SceneryCommentQuery qo) {
        //repository和template无法直接查询分页数据, 所以需要自己封装
        Query query = new Query();
        //查询当前页的list
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        query.with(pageable);
        //拼接查询条件
        if (qo.getSceneryId() != -1) {
            query.addCriteria(Criteria.where("sceneryId").is(qo.getSceneryId()));
        }
        //查总数
        long count = template.count(query, SceneryComment.class);
        if (count == 0) {
            return Page.empty();
        }
        List<SceneryComment> list = template.find(query, SceneryComment.class);
        return new PageImpl(list, pageable, count);
    }


}
